<?

// Mates! - This file contains commonly used functions
// Authors:
//   Ayush Agarwal <yush@umich.edu>
//   Adam Herscher <ahersche@umich.edu>
//   Jeff Powers <jrpowers@umich.edu>

// connect to the database
function db_connect() {
  $db = mysql_connect($GLOBALS['dbhost'], $GLOBALS['dbuser'], $GLOBALS['dbpass']);
  if (!$db)
    return 0;

  if (!mysql_select_db($GLOBALS['dbname']))
    return 0;
  
  return $db;
}

// get a user_id and username from a session_id
function getuser($session_id) {
  $query = "select user_id, username from users where session_id = '$session_id'";
  $res = mysql_query($query);
  
  if (!$res)
    return array(0, db_err($query), 0);
  
  if (!mysql_num_rows($res)) // invalid session
    return array(0, "Invalid session.", 0);

  $row = mysql_fetch_assoc($res);
  return array(1, $row["user_id"], $row["username"]);
}

// get a loc_id from a user_id
function getloc($user_id) {
  $query = "select loc_id from in_loc where user_id = '$user_id'";
  $res = mysql_query($query);
  
  if (!$res)
    return array(0, db_err($querry));
  
  if (!mysql_num_rows($res)) // user has not set a location
    return array(0, "User has not set a location.");

  $row = mysql_fetch_object($res);
  return array(1, $row->loc_id);
}

// remove a user from a location
function exit_loc($user_id, $loc_id, $session_id, $username, $logout) {
  if ($logout)
    $msg_type = "logout";
  else
    $msg_type = "exitloc";

  // delete user from in_loc
  $query = "delete from in_loc where user_id = '$user_id'";
  $res = mysql_query($query);
  if (!$res)
    return array(0, db_err($query));

  // send logout or exitloc notifications to nearby users
  $query = "
select u.session_id
from users u, in_loc in1
where in1.loc_id = '$loc_id' and 
      in1.user_id = u.user_id

union all
select u.session_id
from users u, in_loc in1, loc_rel lr
where lr.loc_id = '$loc_id' and
      in1.loc_id = lr.neighbor_id and
      in1.user_id = u.user_id
      ";
  $res = mysql_query($query);
  if (!$res)
    return array(0, db_err($query));

  while ($row = mysql_fetch_assoc($res)) {
    $query2 = "insert into rel_queue (session_id, username, loc_id, msg_type, rel_type, rel_param, ts) values ('{$row['session_id']}', '$username', '$loc_id', '$msg_type', '', '', NOW())";
    $res2 = mysql_query($query2);
    if (!$res2)
      return array(0, db_err($query2));
  }
  
  // delete stale messages from rel_queue and loc_queue
  $query = "delete from rel_queue where session_id = '$session_id'";
  $res = mysql_query($query);
  if (!$res)
    return array(0, db_err($query));
  $query = "delete from loc_queue where session_id = '$session_id'";
  $res = mysql_query($query);
  if (!$res)
    return array(0, db_err($query));
  
  if ($logout) {
    $query = "delete from msg_queue where session_id = '$session_id'";
    $res = mysql_query($query);
    if (!$res)
      return array(0, db_err($query));

    // notify friends
    $query = "
select session_id
from users, friends
where friends.friend_id = '$user_id' and 
      friends.user_id = users.user_id
    ";
    $res = mysql_query($query);
    if (!$res)
      return array(0, db_err($query));
    while ($row = mysql_fetch_assoc($res)) {
      $query2 = "insert into rel_queue (session_id, username, loc_id, msg_type, rel_type, rel_param, ts) values ('{$row["session_id"]}', '$username', '$loc_id', 'user_off', 'friend', '', NOW())";
      $res2 = mysql_query($query2);
      if (!$res2)
        return array(0, db_err($query));
    }
  }

  return array(1, 0);
}

// common init functions
function init_func() {
  ignore_user_abort(true);
  set_time_limit(300);
}

// validate username
function valid_username($username) {
  if (!ereg("^[a-zA-Z0-9]{3,15}$", $username))
    return 0;
  return 1;
}

// validate password
function valid_password($password) {
  if (!ereg("^[]A-Za-z0-9\(\)\[\^\.\$\|\*\+\?\{\\!@#%&_=};:,<>/~-]{6,20}$", $password))
    return 0;
  return 1;
}

// validate session_id
function valid_session_id($session_id) {
  if (!ereg("^[A-Z]{10}$", $session_id))
    return 0;
  return 1;
}

// validate location name
function valid_location_name($name) {
  if (!ereg("^[]A-Za-z0-9\(\)\[\^\.\$\|\*\+\?\{\\!@#%&_=};:,<>/~ -]{1,50}$", $name))
    return 0;
  return 1;
}

// validate generic string
function valid_generic($str) {
  if (!ereg("^[]A-Za-z0-9\(\)\[\^\.\$\|\*\+\?\{\\!@#%&_=};:,<>/~ -]{1,255}$", $str))
    return 0;
  return 1;
}

// return a mysql database error string
function db_err($query) {
  if ($GLOBALS['show_true_db_errors'])
    return("A fatal MySQL error occured.  QUERY: " . $query . "  ERROR: (" . mysql_errno() . ") " . mysql_error());
  return "Unable to communicate with database.";
}

?>